package com.diaohw.module.websocket.service;

import cn.hutool.extra.spring.SpringUtil;
import com.diaohw.module.websocket.obj.dto.MsgDTO;
import com.diaohw.module.websocket.obj.enums.WSStatusEnums;
import com.diaohw.module.websocket.obj.vo.MsgVO;
import com.diaohw.module.websocket.properties.MsgProcessProperties;
import com.diaohw.module.websocket.properties.WsMessageProperties;
import com.diaohw.module.websocket.service.ws.MessageHandle;
import com.diaohw.module.websocket.service.ws.handle.HttpHandle;
import com.diaohw.module.websocket.service.ws.handle.RabbitMQHandle;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public class MsgService {


    @Resource
    private WsMessageProperties properties;

    private Optional<HttpHandle> httpHandle = Optional.empty();
    private Optional<RabbitMQHandle> rabbitMQHandle = Optional.empty();

    @PostConstruct
    public void init() {
        try {
            httpHandle = Optional.of(SpringUtil.getBean(HttpHandle.class));
        } catch (Exception e) {
            log.error("http handle is not registered!");
        }

        try {
            rabbitMQHandle = Optional.of(SpringUtil.getBean(RabbitMQHandle.class));
        } catch (Exception e) {
            log.error("rabbit mq handle is not registered!");
        }


    }


    public MsgVO send(MsgDTO data) {
        return MessageHandle.sendMessage(data);
    }


    public void process(String topic, String subscribeId, WSStatusEnums type, String message, String token) {

        MsgVO data = MsgVO.of(message, type, topic, subscribeId, true, token);

        MsgProcessProperties config = this.properties.getConfig(topic);
        if (config == null) {
            return;
        }

        if (config.enableHttp()) {
            httpHandle.ifPresent(h -> h.execute(config.getHttp(), data));
        }

        if (config.enableRabbit()) {
            rabbitMQHandle.ifPresent(h -> h.execute(config.getRabbit(), data));
        }
    }

}
